package goodbaby.dklt.fragment;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.classic.core.fragment.BaseFragment;
import com.classic.core.utils.StringUtil;
import com.classic.core.utils.ToastUtil;
import com.classic.okhttp.gbb.http.ActionHelp;
import com.classic.okhttp.gbb.http.ObjectCallback;
import com.google.gson.reflect.TypeToken;
import com.tgd.gbb.uikit.ui.dialog.CommonDialog;
import com.tgd.gbb.uikit.ui.refresh.PullToRefreshScrollView;
import com.tgd.gbb.uikit.ui.refresh.PullToRefreshUtil;
import com.tgd.gbb.uikit.ui.refresh.base.PullToRefreshBase;
import com.tgd.gbb.uikit.ui.widget.EditButtonView;
import com.tgd.gbb.uikit.ui.widget.MyListView;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import goodbaby.dklt.GbbPreferences;
import goodbaby.dklt.R;
import goodbaby.dklt.activity.MainActivity;
import goodbaby.dklt.activity.MessageActivity;
import goodbaby.dklt.activity.UserActivity;
import goodbaby.dklt.adapter.ParentsCircleAdapter;
import goodbaby.dklt.bean.CardBean;
import goodbaby.dklt.bean.ParentsCricleBean;
import goodbaby.dklt.bean.PraiseBean;
import goodbaby.dklt.bean.ReviewBean;
import goodbaby.dklt.bean.SportInfo;

/**
 * Created by Jayden on 2016/4/19 14:01.
 *
 * @version V1.0
 * @Title: HomeFragment
 * @Description: 动态页
 */
public class HomeFragment extends BaseFragment implements EditButtonView.OnButtonClickListener {


    public static int toBigImage = 0;
    private Button btnCard;
    private CardBean card = new CardBean();
    private MainActivity context;
    private CommonDialog delDialog;
    private EditButtonView editButtonView;
    private EditText editText;
    private int getDataType = 0;
    private InputMethodManager inputMethMgr;
    private boolean isHasMore = true;
    private ImageView ivMsg;
    private ImageView ivUser;
    private LinearLayout llAfternoonCard;
    private LinearLayout llAfternoonUnCard;
    private LinearLayout llMorningCard;
    private LinearLayout llMorningUnCard;
    private MyListView lvPc;
    private int mId;
    private int mPosition;
    private String nickname = ":";
    private int pageNum = 1;
    private List<ParentsCricleBean> parentsCricleBeans = new ArrayList();
    private ParentsCircleAdapter pcAdapter;
    private PullToRefreshScrollView psView;
    private TextView tvDistance;
    private TextView tvHot;
    private TextView tvSleep;
    private TextView tvTimeAfternoon;
    private TextView tvTimeMorning;
    private TextView tvTitle;
    private TextView tvWalk;
    private String userId;

    private void card() {
        ActionHelp.gbbCard(getActivity(), new ObjectCallback<String>() {

            public void onError(int paramAnonymousInt) {
                if (paramAnonymousInt == 413) {
                    ToastUtil.showToast(HomeFragment.this.getActivity(), "您的小孩还没有到学校，暂且不能打卡");
                } else if (paramAnonymousInt == 414) {
                    ToastUtil.showToast(HomeFragment.this.getActivity(), "您的小孩还没有离开学校，暂且不能打卡");
                } else {
                    ToastUtil.showToast(HomeFragment.this.getActivity(), "打卡失败");
                }
            }

            public void onSuccess(String paramAnonymousString) {
                ToastUtil.showToast(HomeFragment.this.getActivity(), "打卡成功");
                initCardStatus();
            }

            @Override
            public Type getType() {
                return new TypeToken<String>() {
                }.getType();
            }
        });
    }

    private void delParentCircleMsg(int paramInt) {
        ActionHelp.gbbDelMsg(getActivity(), paramInt, new ObjectCallback<String>() {

            public void onError(int paramAnonymousInt) {
                ToastUtil.showToast(getActivity(), "删除失败!");
            }

            public void onError(int paramAnonymousInt, String paramAnonymousString) {
                super.onError(paramAnonymousInt, paramAnonymousString);
            }

            public void onSuccess(String paramAnonymousString) {
                ToastUtil.showToast(getActivity(), "删除成功!");
                initData();
            }

            @Override
            public Type getType() {
                return new TypeToken<String>() {
                }.getType();
            }
        });
    }

    private void hideSoftInput(View paramView) {
        this.inputMethMgr.hideSoftInputFromWindow(paramView.getWindowToken(), 0);
        this.editButtonView.setVisibility(View.GONE);
        this.editText.clearFocus();
        this.editText.setText("");
        MainActivity.llTabMain.setVisibility(View.VISIBLE);
        MainActivity.leftCenterButton.setVisibility(View.VISIBLE);
    }

    private void initCardStatus() {
        ActionHelp.gbbGetCardMsg(getActivity(), new ObjectCallback<List<CardBean>>() {

            public void onError(int paramAnonymousInt) {
                ToastUtil.showToast(HomeFragment.this.getActivity(), "获取打卡信息失败");
            }

            public void onSuccess(List<CardBean> paramAnonymousList) {
                if (paramAnonymousList.size() > 0) {
                    card = paramAnonymousList.get(0);
                    if (StringUtil.isEmpty(paramAnonymousList.get(0).getTwoCreateOn_Time())) {
                        HomeFragment.this.llAfternoonCard.setVisibility(View.GONE);
                        HomeFragment.this.llAfternoonUnCard.setVisibility(View.VISIBLE);
                        HomeFragment.this.llMorningCard.setVisibility(View.VISIBLE);
                        HomeFragment.this.llMorningUnCard.setVisibility(View.GONE);
                        HomeFragment.this.tvTimeMorning.setText(paramAnonymousList.get(0).getOneCreateOn_Time());
                    } else {
                        HomeFragment.this.llAfternoonCard.setVisibility(View.VISIBLE);
                        HomeFragment.this.llAfternoonUnCard.setVisibility(View.GONE);
                        HomeFragment.this.llMorningCard.setVisibility(View.VISIBLE);
                        HomeFragment.this.llMorningUnCard.setVisibility(View.GONE);
                        HomeFragment.this.tvTimeMorning.setText(paramAnonymousList.get(0).getOneCreateOn_Time());
                        HomeFragment.this.tvTimeAfternoon.setText(paramAnonymousList.get(0).getTwoCreateOn_Time());
                    }
                } else if (paramAnonymousList.size() == 0) {
                    HomeFragment.this.llAfternoonCard.setVisibility(View.GONE);
                    HomeFragment.this.llAfternoonUnCard.setVisibility(View.VISIBLE);
                    HomeFragment.this.llMorningCard.setVisibility(View.GONE);
                    HomeFragment.this.llMorningUnCard.setVisibility(View.VISIBLE);
                }

            }

            @Override
            public Type getType() {
                return new TypeToken<List<CardBean>>() {
                }.getType();
            }
        });
    }

    private void initSportsInfo() {
        ActionHelp.getSportInfo(getActivity(), new ObjectCallback<SportInfo>() {

            public void onError(int paramAnonymousInt) {
                ToastUtil.showToast(HomeFragment.this.getActivity(), "请求错误");
                HomeFragment.this.tvWalk.setText("--");
                HomeFragment.this.tvHot.setText("--Cal");
                HomeFragment.this.tvDistance.setText("--M");
                HomeFragment.this.tvSleep.setText("--%");
            }

            public void onSuccess(SportInfo paramAnonymousSportInfo) {
                HomeFragment.this.tvWalk.setText(paramAnonymousSportInfo.getSportStep() + "");
                HomeFragment.this.tvHot.setText(paramAnonymousSportInfo.getTakeEnergy() + "Cal");
                HomeFragment.this.tvDistance.setText(paramAnonymousSportInfo.getSRange() + "M");
                HomeFragment.this.tvSleep.setText(paramAnonymousSportInfo.getFinishValue() + "%");
            }

            @Override
            public Type getType() {
                return new TypeToken<SportInfo>() {
                }.getType();
            }
        });
    }

    private void loadMore() {
        if (isHasMore) {
            getDataType = 2;
            pageNum++;
            initData();
            PullToRefreshUtil.initLabel(getActivity(), psView);
        } else {
            PullToRefreshUtil.setLoadLabel(psView, "没有更多了");
            psView.onRefreshComplete();
        }
    }

    private void refrush() {
        getDataType = 1;
        pageNum = 1;
        PullToRefreshUtil.initLabel(getActivity(), psView);
        initData();
    }

    private void showInputSoft(int paramInt) {
        mPosition = paramInt;
        editButtonView.setVisibility(View.GONE);
        editText.requestFocus();
        inputMethMgr.showSoftInput(editText, InputMethodManager.SHOW_FORCED);
        MainActivity.llTabMain.setVisibility(View.VISIBLE);
        MainActivity.leftCenterButton.setVisibility(View.VISIBLE);
    }

    private void submitComment(int paramInt1, String paramString, final int paramInt2) {
        ActionHelp.gbbPubComment(getActivity(), paramInt1, paramInt2, paramString, new ObjectCallback<String>() {

            public void onError(int paramAnonymousInt) {
                if (paramInt2 == 0)
                    ToastUtil.showToast(HomeFragment.this.getActivity(), "评论失败");
            }

            public void onSuccess(String paramAnonymousString) {
                if (paramInt2 == 0)
                    ToastUtil.showToast(HomeFragment.this.getActivity(), "评论成功");
            }

            @Override
            public Type getType() {
                return new TypeToken<String>() {
                }.getType();
            }
        });
    }

    public void closeBottom() {
        editButtonView.setVisibility(View.GONE);
        this.editText.requestFocus();
        MainActivity.llTabMain.setVisibility(View.GONE);
        MainActivity.leftCenterButton.setVisibility(View.GONE);
    }

    public int getLayoutResId() {
        return R.layout.fragment_home;
    }

    public boolean getUserVisibleHint() {
        return super.getUserVisibleHint();
    }

    public void initData() {
        super.initData();
        this.nickname = GbbPreferences.getChildrenName();
        ActionHelp.gbbMessages(getActivity(), this.pageNum, new ObjectCallback<List<ParentsCricleBean>>() {

                    public void onError(int paramAnonymousInt) {
                        if (getDataType != 0)
                            psView.onRefreshComplete();
                    }

                    public void onError(int paramAnonymousInt, String paramAnonymousString) {
                        super.onError(paramAnonymousInt, paramAnonymousString);
                    }

                    public void onSuccess(List<ParentsCricleBean> paramAnonymousList) {
                        if (getDataType != 0) {
                            psView.onRefreshComplete();
                        }
                        if (paramAnonymousList != null) {
                            if (paramAnonymousList.size() < 10) {
                                isHasMore = false;
                            } else {
                                isHasMore = true;
                            }
                            if (getDataType != 2) {
                                parentsCricleBeans.clear();
                            }
                            if (HomeFragment.toBigImage == 0) {
                                parentsCricleBeans.addAll(paramAnonymousList);
                            }
                            pcAdapter = new ParentsCircleAdapter(getActivity(), parentsCricleBeans, new HomeFragment.MyCallBack());
                            lvPc.setAdapter(pcAdapter);
                            pcAdapter.notifyDataSetChanged();
                        }

                        psView.onRefreshComplete();
                    }


                    @Override
                    public Type getType() {
                        return new TypeToken<List<ParentsCricleBean>>() {
                        }.getType();
                    }
                }

        );
    }

    public void initView(View paramView) {
        super.initView(paramView);
        context = new MainActivity();
        tvTitle = (TextView) paramView.findViewById(R.id.tv_common_title);
        tvTitle.setText("乖宝贝");
        ivMsg = (ImageView) paramView.findViewById(R.id.iv_common_msg);
        ivMsg.setVisibility(View.VISIBLE);
        ivMsg.setOnClickListener(this);
        ivUser = (ImageView) paramView.findViewById(R.id.iv_common_user);
        ivUser.setVisibility(View.VISIBLE);
        ivUser.setOnClickListener(this);
        psView = (PullToRefreshScrollView) paramView.findViewById(R.id.om_my_wallet_psv);
        lvPc = (MyListView) paramView.findViewById(R.id.lv_home);
        View localView = getActivity().getLayoutInflater().inflate(R.layout.home_header, null);
        btnCard = (Button) localView.findViewById(R.id.btn_card);
        btnCard.setOnClickListener(this);
        llAfternoonCard = (LinearLayout) localView.findViewById(R.id.ll_card_afternoon_card);
        llAfternoonUnCard = (LinearLayout) localView.findViewById(R.id.ll_card_afternoon_uncard);
        llMorningCard = (LinearLayout) localView.findViewById(R.id.ll_card_morning_card);
        llMorningUnCard = (LinearLayout) localView.findViewById(R.id.ll_card_morning_uncard);
        tvTimeMorning = (TextView) localView.findViewById(R.id.tv_card_time_morning);
        tvTimeAfternoon = (TextView) localView.findViewById(R.id.tv_card_time_afternoon);
        tvHot = (TextView) localView.findViewById(R.id.tv_hot);
        tvDistance = (TextView) localView.findViewById(R.id.tv_distance);
        tvSleep = (TextView) localView.findViewById(R.id.tv_sleep);
        tvWalk = (TextView) localView.findViewById(R.id.tv_walk);
        lvPc.addHeaderView(localView);
        editButtonView = (EditButtonView) paramView.findViewById(R.id.editButtonView);
        editButtonView.setOnButtonClickListener(this);
        editText = this.editButtonView.getEditText();
        inputMethMgr = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        psView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ScrollView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ScrollView> refreshView) {
                if (psView.isHeaderShown()) {
                    refrush();
                } else if (psView.isFooterShown()) {
                    loadMore();
                }
            }
        });
        initCardStatus();
        initSportsInfo();
    }


    public void onButtonClick() {
        String str = this.editButtonView.getContent();
        if (TextUtils.isEmpty(str)) {
            Toast.makeText(getActivity(), getString(R.string.please_input_content), Toast.LENGTH_SHORT).show();
            return;
        }
        submitComment(mId, str, 0);
        ReviewBean localReviewBean = new ReviewBean();
        localReviewBean.setChildrenName(nickname + "家长");
        localReviewBean.setText(str);
        parentsCricleBeans.get(this.mPosition).getReviewlist().add(localReviewBean);
        pcAdapter.notifyDataSetChanged();
        hideSoftInput(editText);
    }

    public void onDestroyView() {
        super.onDestroyView();
    }

    public void onResume() {
        super.onResume();
        if (toBigImage == 0) {
            this.parentsCricleBeans.clear();
            this.pageNum = 1;
            initData();
        }
        toBigImage = 0;
    }

    public void setUserVisibleHint(boolean paramBoolean) {
        super.setUserVisibleHint(paramBoolean);
    }

    public void showBottom() {
        this.editButtonView.setVisibility(View.GONE);
        this.editText.clearFocus();
        this.editText.setText("");
        MainActivity.llTabMain.setVisibility(View.VISIBLE);
        MainActivity.leftCenterButton.setVisibility(View.VISIBLE);
    }

    public void viewClick(View paramView) {
        super.viewClick(paramView);
        switch (paramView.getId()) {
            default:
                return;
            case R.id.iv_common_user:
                startActivity(new Intent(getActivity(), UserActivity.class));
                return;
            case R.id.iv_common_msg:
                startActivity(new Intent(getActivity(), MessageActivity.class));
                return;
            case R.id.btn_card:
                if (!StringUtil.isEmpty(this.card.getTwoCreateOn_Time())) {
                    ToastUtil.showToast(getActivity(), "今天已经完成打卡,请勿重复打卡！");
                    return;
                }
                card();
                break;
        }

    }

    public class MyCallBack
            implements ParentsCircleAdapter.ICallBack {
        public MyCallBack() {
        }

        public void AddComment(int position, int id) {
            mPosition = position;
            mId = id;
            showInputSoft(position);
        }

        public void deleMsg(int position, final int id) {
            mPosition = position;
            mId = id;
            delDialog = new CommonDialog(getActivity()) {
                protected void clickCancel(View paramAnonymousView) {
                    super.clickCancel(paramAnonymousView);
                    dismiss();
                }

                protected void clickOk(View paramAnonymousView) {
                    super.clickOk(paramAnonymousView);
                    delParentCircleMsg(id);
                }
            };
            delDialog.show();
        }

        public void praise(int position, int id) {
            mPosition = position;
            mId = id;
            userId = GbbPreferences.getUserId();
            Integer.parseInt(HomeFragment.this.userId);
            int i = 0;
            Iterator localIterator = ((ParentsCricleBean) HomeFragment.this.parentsCricleBeans.get(HomeFragment.this.mPosition)).getPraiselist().iterator();
            while (true) {
                boolean bool = localIterator.hasNext();
                int j = 0;
                if (bool) {
                    if (((PraiseBean) localIterator.next()).getIS_PRAISE() == 1)
                        j = 0 + 1;
                } else {
                    if (j != 0)
                        break;
                    HomeFragment.this.submitComment(HomeFragment.this.mId, "", 1);
                    PraiseBean localPraiseBean = new PraiseBean();
                    localPraiseBean.setChildrenName(HomeFragment.this.nickname);
                    localPraiseBean.setIS_PRAISE(1);
                    ((ParentsCricleBean) HomeFragment.this.parentsCricleBeans.get(HomeFragment.this.mPosition)).getPraiselist().add(localPraiseBean);
                    HomeFragment.this.pcAdapter.notifyDataSetChanged();
                    return;
                }
                i++;
            }
            HomeFragment.this.submitComment(HomeFragment.this.mId, "", 2);
            ((ParentsCricleBean) HomeFragment.this.parentsCricleBeans.get(HomeFragment.this.mPosition)).getPraiselist().remove(i);
            HomeFragment.this.pcAdapter.notifyDataSetChanged();
        }

        public void redirect(int position, int id) {
        }
    }

}
